import PubSub from 'pubsub-js'
import { requestData } from "../../config/requestData"
import { recommendUrl } from '../../config/api'
// pages/recommendSong/recommendSong.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        day: 0,
        month: 0,
        recommendList: [], //推荐歌曲
        index: 0, //歌曲下标
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.loadingTimeData()
        this.loadingRecommendData()
        this.loadingChangeTypeData()
    },
    handleSongDetail (e) {
        const id = e.currentTarget.dataset.id
        wx.navigateTo({
          url: `/pages/songDetail/songDetail?id=${id}`
        })
    },
    // 加载方式
    loadingChangeTypeData() {
        let { recommendList, index } = this.data
        PubSub.subscribe('changeTypeData', (msg, type) => {
            if (type === 'next') {
                (index = recommendList.length - 1) && (index === 0)
                index += 1
            }else{
                (index = 0) && (index === recommendList.length)
                index -= 1
            }
            this.setData({
                index
            })
            let musicId = recommendList[index].id
            PubSub.publish('musicId', musicId)
        })
    },
    loadingTimeData () {
        let month = new Date().getMonth() + 1
        let day = new Date().getDate()
        this.setData({
            day,
            month
        })
    },
    async loadingRecommendData () {
        const options = {
            url: recommendUrl
        }
        const res = await requestData(options)
        const { code, recommend } = res
        if (code === 200) {
            this.setData({
                recommendList: recommend
            })
        }
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})